package api

import (
	"net/http"

	"example.com/rest/example/dao"
	"example.com/rest/example/model"

	"github.com/gin-gonic/gin"
	"github.com/guregu/null"
	"github.com/julienschmidt/httprouter"
)

var (
	_ = null.Bool{}
)

func configPurchaseOrderRouter(router *httprouter.Router) {
	router.GET("/purchaseorder", GetAllPurchaseOrder)
	router.POST("/purchaseorder", AddPurchaseOrder)
	router.GET("/purchaseorder/:argId", GetPurchaseOrder)
	router.PUT("/purchaseorder/:argId", UpdatePurchaseOrder)
	router.DELETE("/purchaseorder/:argId", DeletePurchaseOrder)
}

func configGinPurchaseOrderRouter(router gin.IRoutes) {
	router.GET("/purchaseorder", ConverHttprouterToGin(GetAllPurchaseOrder))
	router.POST("/purchaseorder", ConverHttprouterToGin(AddPurchaseOrder))
	router.GET("/purchaseorder/:argId", ConverHttprouterToGin(GetPurchaseOrder))
	router.PUT("/purchaseorder/:argId", ConverHttprouterToGin(UpdatePurchaseOrder))
	router.DELETE("/purchaseorder/:argId", ConverHttprouterToGin(DeletePurchaseOrder))
}

// GetAllPurchaseOrder is a function to get a slice of record(s) from purchase_order table in the main database
// @Summary Get list of PurchaseOrder
// @Tags PurchaseOrder
// @Description GetAllPurchaseOrder is a handler to get a slice of record(s) from purchase_order table in the main database
// @Accept  json
// @Produce  json
// @Param   page     query    int     false        "page requested (defaults to 0)"
// @Param   pagesize query    int     false        "number of records in a page  (defaults to 20)"
// @Param   order    query    string  false        "db sort order column"
// @Success 200 {object} api.PagedResults{data=[]model.PurchaseOrder}
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /purchaseorder [get]
// http "http://localhost:8080/purchaseorder?page=0&pagesize=20" X-Api-User:user123
func GetAllPurchaseOrder(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	page, err := readInt(r, "page", 0)
	if err != nil || page < 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	pagesize, err := readInt(r, "pagesize", 20)
	if err != nil || pagesize <= 0 {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	order := r.FormValue("order")

	if err := ValidateRequest(ctx, r, "purchase_order", model.RetrieveMany); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	records, totalRows, err := dao.GetAllPurchaseOrder(ctx, page, pagesize, order)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	result := &PagedResults{Page: page, PageSize: pagesize, Data: records, TotalRecords: totalRows}
	writeJSON(ctx, w, result)
}

// GetPurchaseOrder is a function to get a single record from the purchase_order table in the main database
// @Summary Get record from table PurchaseOrder by  argId
// @Tags PurchaseOrder
// @ID argId
// @Description GetPurchaseOrder is a function to get a single record from the purchase_order table in the main database
// @Accept  json
// @Produce  json
// @Param  argId path int true "id"
// @Success 200 {object} model.PurchaseOrder
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError "ErrNotFound, db record for id not found - returns NotFound HTTP 404 not found error"
// @Router /purchaseorder/{argId} [get]
// http "http://localhost:8080/purchaseorder/1" X-Api-User:user123
func GetPurchaseOrder(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseInt32(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "purchase_order", model.RetrieveOne); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	record, err := dao.GetPurchaseOrder(ctx, argId)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, record)
}

// AddPurchaseOrder add to add a single record to purchase_order table in the main database
// @Summary Add an record to purchase_order table
// @Description add to add a single record to purchase_order table in the main database
// @Tags PurchaseOrder
// @Accept  json
// @Produce  json
// @Param PurchaseOrder body model.PurchaseOrder true "Add PurchaseOrder"
// @Success 200 {object} model.PurchaseOrder
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /purchaseorder [post]
// echo '{"id": 2,"payment_id": 74,"full_name": "yKaUjopVmgNirKKOaalVHmuCC"}' | http POST "http://localhost:8080/purchaseorder" X-Api-User:user123
func AddPurchaseOrder(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)
	purchaseorder := &model.PurchaseOrder{}

	if err := readJSON(r, purchaseorder); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := purchaseorder.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	purchaseorder.Prepare()

	if err := purchaseorder.Validate(model.Create); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "purchase_order", model.Create); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	var err error
	purchaseorder, _, err = dao.AddPurchaseOrder(ctx, purchaseorder)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, purchaseorder)
}

// UpdatePurchaseOrder Update a single record from purchase_order table in the main database
// @Summary Update an record in table purchase_order
// @Description Update a single record from purchase_order table in the main database
// @Tags PurchaseOrder
// @Accept  json
// @Produce  json
// @Param  argId path int true "id"
// @Param  PurchaseOrder body model.PurchaseOrder true "Update PurchaseOrder record"
// @Success 200 {object} model.PurchaseOrder
// @Failure 400 {object} api.HTTPError
// @Failure 404 {object} api.HTTPError
// @Router /purchaseorder/{argId} [put]
// echo '{"id": 2,"payment_id": 74,"full_name": "yKaUjopVmgNirKKOaalVHmuCC"}' | http PUT "http://localhost:8080/purchaseorder/1"  X-Api-User:user123
func UpdatePurchaseOrder(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseInt32(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	purchaseorder := &model.PurchaseOrder{}
	if err := readJSON(r, purchaseorder); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := purchaseorder.BeforeSave(); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
	}

	purchaseorder.Prepare()

	if err := purchaseorder.Validate(model.Update); err != nil {
		returnError(ctx, w, r, dao.ErrBadParams)
		return
	}

	if err := ValidateRequest(ctx, r, "purchase_order", model.Update); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	purchaseorder, _, err = dao.UpdatePurchaseOrder(ctx,
		argId,
		purchaseorder)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeJSON(ctx, w, purchaseorder)
}

// DeletePurchaseOrder Delete a single record from purchase_order table in the main database
// @Summary Delete a record from purchase_order
// @Description Delete a single record from purchase_order table in the main database
// @Tags PurchaseOrder
// @Accept  json
// @Produce  json
// @Param  argId path int true "id"
// @Success 204 {object} model.PurchaseOrder
// @Failure 400 {object} api.HTTPError
// @Failure 500 {object} api.HTTPError
// @Router /purchaseorder/{argId} [delete]
// http DELETE "http://localhost:8080/purchaseorder/1" X-Api-User:user123
func DeletePurchaseOrder(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	ctx := initializeContext(r)

	argId, err := parseInt32(ps, "argId")
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	if err := ValidateRequest(ctx, r, "purchase_order", model.Delete); err != nil {
		returnError(ctx, w, r, err)
		return
	}

	rowsAffected, err := dao.DeletePurchaseOrder(ctx, argId)
	if err != nil {
		returnError(ctx, w, r, err)
		return
	}

	writeRowsAffected(w, rowsAffected)
}
